package com.zty.service.impl;

import com.zty.domain.LoginUser;
import com.zty.domain.ResponseResult;
import com.zty.domain.User;
import com.zty.domain.dto.passwordDTO;
import com.zty.mapper.UserMapper;
import com.zty.service.LoginService;
import com.zty.utils.JwtUtil;
import com.zty.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @version V1.0
 * @ClassName: com.zty.service.impl.LoginServiceImpl.java
 * @Copyright swpu
 * @author: zty-f
 * @date: 2022-11-25 20:51
 * @Description:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(User user) {
        //调用AuthenticationManager authenticationManager进行用户认证  用户账号，用户密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出提示
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登录失败！");
        }
        //认证通过，使用userid生成jwt返回前端，并userid为key，用户信息为value存入redis
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        //这里jwt增强token
        String jwt = JwtUtil.createJWT(userId);
        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);

        //这里存进redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        return new ResponseResult(200,"登录成功",map);
    }

    @Override
    public ResponseResult loginOut() {
        //获取SecurityContextHolder中的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       // System.out.println("authentication ================ " + authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userID = loginUser.getUser().getId().toString();
        //删除redis中的值
        redisCache.deleteObject("login:"+userID);
        return new ResponseResult(200,"注销成功");
    }

    @Override
    public ResponseResult updateUser(passwordDTO pw) {
        //传入 id ,password
        Long id = pw.getId();
        String password = pw.getPassword();
        //加密
        String encodePassword = passwordEncoder.encode(password);
        //修改存入数据库
        User user =new User();
        user.setId(id);
        user.setPassword(encodePassword);
        int i = userMapper.updateById(user);
        return i>0 ? new ResponseResult(200,"改密成功") : new ResponseResult(500,"改密失败");
    }
}
